
package cn.itcast.controller;


import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Member;
import cn.itcast.service.MemberService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping(path = "/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


        /**
         *  用户登录请
         */
    @PostMapping(path = "/login")
    public Result login(@RequestBody Map<String, String> map, HttpServletResponse response) {
        String phone = (String) map.get("phone");
        String validateCode = (String) map.get("validateCode");

        String LOGIN_CODE = "REDIS_LOGIN_CODE" + phone;

        //获取redis中验证码
        String code = this.redisTemplate.opsForValue().get(LOGIN_CODE);
        if (!StringUtils.equals(code, validateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //判断当前用户是否为会员
        Member member = memberService.findByTelephone(phone);
        if (member == null) {
            //当前用户不是会员，自动完成注册
            member = new Member();
            //手机号
            member.setPhoneNumber(phone);
            //注册时间
            member.setRegTime(new Date());
            member.setStatus(0);
            memberService.add(member);
        }

       /* HashMap<String, Object> claims = new HashMap<>();
        claims.put("login_member_telephone",phone);
        String token = Jwts.builder()
                .setClaims(claims) //payload 存储数据的位置,不放敏感数据
                .signWith(SignatureAlgorithm.HS256, score)//设置加密方法和密盐
                .setExpiration(new DateTime().plusHours(12).toDate())  //设置过期时间
                .compact();//plusHours*/

        //写入
        /*Cookie cookie = new Cookie("login_member_telephone",phone);
        cookie.setPath("/");//路径
        cookie.setMaxAge(60*60*24*30);//有效期30天
        response.addCookie(cookie);*/

        return new Result(true, MessageConstant.LOGIN_SUCCESS,phone);
    }
}

